import { useState, useEffect } from 'react';
import { useGameState } from '../game/GameState';
import { Play, Users, Search, Clock } from 'lucide-react';

/**
 * 赛博侦探游戏主页
 * 提供游戏开始界面和基本的游戏控制
 */
export default function Home() {
  const {
    gamePhase,
    currentCase,
    suspects,
    conversationHistory,
    timeRemaining,
    startNewCase,
    askQuestion,
    updateTimeRemaining
  } = useGameState();
  
  const [selectedSuspect, setSelectedSuspect] = useState<string>('');
  const [question, setQuestion] = useState<string>('');
  const [isLoading, setIsLoading] = useState<boolean>(false);

  /**
   * 游戏计时器
   */
  useEffect(() => {
    let timer: NodeJS.Timeout;
    
    if (gamePhase === 'investigation' && timeRemaining > 0) {
      timer = setInterval(() => {
        updateTimeRemaining(timeRemaining - 1);
      }, 1000);
    }
    
    return () => {
      if (timer) {
        clearInterval(timer);
      }
    };
  }, [gamePhase, timeRemaining, updateTimeRemaining]);

  /**
   * 开始新游戏
   */
  const handleStartGame = async () => {
    setIsLoading(true);
    try {
      await startNewCase();
    } catch (error) {
      console.error('开始游戏失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 提交问题给嫌疑人
   */
  const handleAskQuestion = async () => {
    if (!selectedSuspect || !question.trim()) {
      alert('请选择嫌疑人并输入问题');
      return;
    }
    
    setIsLoading(true);
    try {
      await askQuestion(question, selectedSuspect);
      setQuestion('');
    } catch (error) {
      console.error('提问失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  /**
   * 格式化时间显示
   */
  const formatTime = (seconds: number): string => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-purple-900 via-blue-900 to-indigo-900 text-white">
      <div className="container mx-auto px-4 py-8">
        {/* 游戏标题 */}
        <div className="text-center mb-8">
          <h1 className="text-5xl font-bold mb-4 bg-gradient-to-r from-cyan-400 to-purple-400 bg-clip-text text-transparent">
            赛博侦探游戏
          </h1>
          <p className="text-xl text-gray-300">
            在未来世界中解开谜团，找出真相
          </p>
        </div>

        {/* 游戏状态 */}
        {gamePhase === 'menu' && (
          <div className="text-center">
            <div className="bg-black/30 backdrop-blur-sm rounded-lg p-8 max-w-md mx-auto">
              <Play className="w-16 h-16 mx-auto mb-4 text-cyan-400" />
              <h2 className="text-2xl font-bold mb-4">准备开始调查</h2>
              <p className="text-gray-300 mb-6">
                一起案件等待你的调查。运用你的推理能力，
                通过询问嫌疑人找出真相。
              </p>
              <button
                onClick={handleStartGame}
                disabled={isLoading}
                className="bg-gradient-to-r from-cyan-500 to-purple-500 hover:from-cyan-600 hover:to-purple-600 disabled:opacity-50 px-8 py-3 rounded-lg font-bold text-lg transition-all duration-200 transform hover:scale-105"
              >
                {isLoading ? '生成案件中...' : '开始游戏'}
              </button>
            </div>
          </div>
        )}

        {/* 案件生成中 */}
        {gamePhase === 'case-gen' && (
          <div className="text-center">
            <div className="bg-black/30 backdrop-blur-sm rounded-lg p-8 max-w-md mx-auto">
              <div className="animate-spin w-16 h-16 border-4 border-cyan-400 border-t-transparent rounded-full mx-auto mb-4"></div>
              <h2 className="text-2xl font-bold mb-4">正在生成案件...</h2>
              <p className="text-gray-300">
                AI正在为你创建一个独特的推理案件
              </p>
            </div>
          </div>
        )}

        {/* 调查阶段 */}
        {gamePhase === 'investigation' && currentCase && (
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* 案件信息 */}
            <div className="lg:col-span-2">
              <div className="bg-black/30 backdrop-blur-sm rounded-lg p-6 mb-6">
                <div className="flex items-center justify-between mb-4">
                  <h2 className="text-2xl font-bold text-cyan-400">{currentCase.title}</h2>
                  <div className="flex items-center text-yellow-400">
                    <Clock className="w-5 h-5 mr-2" />
                    <span className="text-lg font-mono">{formatTime(timeRemaining)}</span>
                  </div>
                </div>
                <p className="text-gray-300 mb-4">{currentCase.description}</p>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className="text-gray-400">地点：</span>
                    <span>{currentCase.location}</span>
                  </div>
                  <div>
                    <span className="text-gray-400">时间：</span>
                    <span>{currentCase.timeOfCrime}</span>
                  </div>
                  <div>
                    <span className="text-gray-400">受害者：</span>
                    <span>{currentCase.victim}</span>
                  </div>
                </div>
              </div>

              {/* 嫌疑人列表 */}
              <div className="bg-black/30 backdrop-blur-sm rounded-lg p-6 mb-6">
                <div className="flex items-center mb-4">
                  <Users className="w-6 h-6 mr-2 text-purple-400" />
                  <h3 className="text-xl font-bold">嫌疑人</h3>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  {suspects.map((suspect) => (
                    <div
                      key={suspect.id}
                      onClick={() => setSelectedSuspect(suspect.id)}
                      className={`p-4 rounded-lg border-2 cursor-pointer transition-all duration-200 ${
                        selectedSuspect === suspect.id
                          ? 'border-cyan-400 bg-cyan-400/10'
                          : 'border-gray-600 hover:border-gray-400'
                      }`}
                    >
                      <h4 className="font-bold text-lg mb-2">{suspect.name}</h4>
                      <p className="text-sm text-gray-300 mb-2">{suspect.background}</p>
                      <p className="text-xs text-gray-400">不在场证明：{suspect.alibi}</p>
                      <div className="mt-2">
                        <span className="text-xs text-yellow-400">
                          可疑度：{suspect.suspicionLevel}/10
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* 提问区域 */}
              <div className="bg-black/30 backdrop-blur-sm rounded-lg p-6">
                <div className="flex items-center mb-4">
                  <Search className="w-6 h-6 mr-2 text-green-400" />
                  <h3 className="text-xl font-bold">询问嫌疑人</h3>
                </div>
                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium mb-2">
                      选择嫌疑人：
                    </label>
                    <select
                      value={selectedSuspect}
                      onChange={(e) => setSelectedSuspect(e.target.value)}
                      className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white"
                    >
                      <option value="">请选择嫌疑人</option>
                      {suspects.map((suspect) => (
                        <option key={suspect.id} value={suspect.id}>
                          {suspect.name}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className="block text-sm font-medium mb-2">
                      你的问题：
                    </label>
                    <textarea
                      value={question}
                      onChange={(e) => setQuestion(e.target.value)}
                      placeholder="输入你想问的问题..."
                      className="w-full bg-gray-800 border border-gray-600 rounded-lg px-3 py-2 text-white h-24 resize-none"
                    />
                  </div>
                  <button
                    onClick={handleAskQuestion}
                    disabled={isLoading || !selectedSuspect || !question.trim()}
                    className="w-full bg-gradient-to-r from-green-500 to-blue-500 hover:from-green-600 hover:to-blue-600 disabled:opacity-50 px-4 py-2 rounded-lg font-bold transition-all duration-200"
                  >
                    {isLoading ? '询问中...' : '提问'}
                  </button>
                </div>
              </div>
            </div>

            {/* 对话历史 */}
            <div className="lg:col-span-1">
              <div className="bg-black/30 backdrop-blur-sm rounded-lg p-6 h-full">
                <h3 className="text-xl font-bold mb-4 text-purple-400">对话记录</h3>
                <div className="space-y-4 max-h-96 overflow-y-auto">
                  {conversationHistory.length === 0 ? (
                    <p className="text-gray-400 text-center">还没有对话记录</p>
                  ) : (
                    conversationHistory.map((conversation) => {
                      const suspect = suspects.find(s => s.id === conversation.suspectId);
                      return (
                        <div key={conversation.id} className="border-l-4 border-cyan-400 pl-4">
                          <div className="text-sm text-gray-400 mb-1">
                            询问 {suspect?.name}
                          </div>
                          <div className="text-sm mb-2 text-yellow-300">
                            问：{conversation.question}
                          </div>
                          <div className="text-sm text-green-300">
                            答：{conversation.response}
                          </div>
                          <div className="text-xs text-gray-500 mt-1">
                            可疑度：{conversation.suspicionLevel}/10
                          </div>
                        </div>
                      );
                    })
                  )}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* 结案阶段 */}
        {gamePhase === 'reveal' && (
          <div className="text-center">
            <div className="bg-black/30 backdrop-blur-sm rounded-lg p-8 max-w-md mx-auto">
              <h2 className="text-2xl font-bold mb-4">案件结束</h2>
              <p className="text-gray-300 mb-6">
                时间到了！请提交你的推理结果。
              </p>
              <button
                onClick={() => window.location.reload()}
                className="bg-gradient-to-r from-purple-500 to-pink-500 hover:from-purple-600 hover:to-pink-600 px-8 py-3 rounded-lg font-bold text-lg transition-all duration-200 transform hover:scale-105"
              >
                重新开始
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}